package com.dartfar.base.action;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dartfar.base.model.Function;
import com.dartfar.base.model.Person;
import com.dartfar.base.model.T_User;
import com.dartfar.base.vo.FunctionVo;
import com.dartfar.dictionary.model.Dictionary;
import com.dartfar.dictionary.vo.DictionaryVo;
import com.dartfar.organize.model.Department;
import com.dartfar.util.EntityUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


/**
 * 通用Action
 * @author 王琦
 */
@Scope("prototype")
@Component("baseAction")
public class BaseAction extends ActionSupport implements ServletResponseAware, SessionAware {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	static Logger logger = Logger.getLogger(BaseAction.class);
	
	/**
	 * session对象
	 */
	protected Map<String, Object> session;
	
	/**
	 * response对象
	 */
	protected HttpServletResponse response; 
	
	
	/**
	 * 页面传参
	 */
	protected int id;				//编号
	
	protected int wid;				//菜单编号
	
	protected int pageNo = 1;		//分页页码
	protected int pageSize = 15;	//页面大小
	
	protected String autCode;		//权限代码
	
	private String dictCode;	//字典代码
	private String dictKey;		//字典KEY
	
	protected String modelName;		//模型名称
	protected String modelIdName;	//模型ID名称
	protected String assigneType;	//委托类型
	protected String assigneRoles;	//委托角色
	protected String assignees;		//委托人
	
	protected List<FunctionVo> functions;	//功能列表
	
	//protected List workflowButtons;
	
	protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	

	protected Map curSession(){
		//实例化 ActionContext
		ActionContext actionContext = ActionContext.getContext();
		//实例化  session
	    Map session = actionContext.getSession();
		return session;
	}
	
	protected Integer curWid(){
		wid = (Integer)curSession().get("wid");
		logger.info("WID: " + wid);
		return wid;
	}
	
	/**
	 * 获取当前用户信息
	 */
	protected T_User curUser(){
	    //从SESSION中获取USER
		return (T_User)curSession().get("user");
	}
	
	/**
	 * 获取当前人员信息
	 */
	protected Person curPerson(){
		return (Person)curSession().get("person");
	}
	
	/**
	 * 获取当前部门信息
	 */
	protected Department curDepart(){
		return (Department)curSession().get("depart");
	}

	/**
	 * 将数组转成JSON发送给前台
	 * @param obj
	 */
	protected void toWriteArray(Object obj){
		try {
			String jsonResult = JSONArray.fromObject(obj).toString();
			logger.info("jsonResult: " + jsonResult);
			response.getWriter().write(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 将对象转成JSON发送给前台
	 * @param obj
	 */
	protected void toWriteObject(Object obj){
		try {
			String jsonResult = JSONObject.fromObject(obj).toString();
			logger.info("jsonResult: " + jsonResult);
			response.getWriter().write(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取当前权限信息
	 */
	protected List<Function> curPermissions(Integer cpWid){
		List<Function> list;
		//从SESSION中 获取功能列表
		Map functionMap = (Map)curSession().get("function");	
		
		if(EntityUtils.isNotNull(cpWid)){
			logger.info("cpWid: " + cpWid);
			list = (List<Function>)functionMap.get("menu" + cpWid);
		}else{
			logger.info("cpWid: " + curWid());
			list = (List<Function>)functionMap.get("menu" + curWid());
		}
		return list;
	}
	
	/**
	 * 根据字典代码和字典键获取值
	 */
	protected String dict(String dictCode, String key){
		ServletContext context = ServletActionContext.getServletContext();  
	    HashMap dictMap = (HashMap)context.getAttribute("dictMap");
	    HashMap dMap = (HashMap) dictMap.get(dictCode);
		return (String) dMap.get(key);
	}

	/**
	 * 获取当前功能列表
	 */
	@SuppressWarnings("unchecked")
	protected List<FunctionVo> getAutFunctions(){
		//获取当前角色当前菜单所有权限
		//List<Authority> authoritys = curAuthoritys();
		List<Function> functions = curPermissions(null);
		List<FunctionVo> functionVos = new ArrayList<FunctionVo>();
		for(Iterator<Function> funcs = functions.iterator(); funcs.hasNext();){
			Function func = funcs.next();
			FunctionVo funVo = new FunctionVo();
			funVo.setId(func.getId());
			funVo.setFuncode(func.getFuncode());
			funVo.setCode(func.getCode());
			funVo.setName(func.getName());
			funVo.setBtnCode(func.getFuncode());
			functionVos.add(funVo);
			logger.info("FunName: " + func.getName());
		}
		return functionVos;
	}
	
	/**
	 * 获取当前删除权限
	 */
	@SuppressWarnings("unchecked")
	protected List<Function> curAutDel(){
		//获取当前角色当前菜单所有权限
		List<Function> functions = curPermissions(wid);
		//初始化 功能列表
		List<Function> delFuns = new ArrayList<Function>();
		//遍历功能
		for(Iterator<Function> f = functions.iterator();f.hasNext();){
			//实体化对象
			Function func = f.next();
			//如果FunCode 等于 edit
			if(func.getCode().equalsIgnoreCase("del")){
				logger.info("curAutDel: " + func.getDes());
				//增加到编辑功能中
				delFuns.add(func);
			}
		}
		return delFuns;
	}
	
	
	/**
	 * 获取当前浏览权限
	 */
	@SuppressWarnings("unchecked")
	protected List<Function> curAutView(){
		
		//获取当前角色当前菜单所有权限
		List<Function> functions = curPermissions(wid);
		//初始化 功能列表
		List<Function> viewFuns = new ArrayList<Function>();
		//遍历功能
		for(Iterator<Function> f = functions.iterator();f.hasNext();){
			//实体化对象
			Function func = f.next();
			//如果FunCode 等于 edit
			if(func.getCode().equalsIgnoreCase("view")){
				logger.info("curAutView: " + func.getDes());
				//增加到编辑功能中
				viewFuns.add(func);
			}
		}
		return viewFuns;
	}
	
	/**
	 * 获取当前编辑权限
	 */
	@SuppressWarnings("unchecked")
	protected List<Function> curAutEdit(){
		//获取当前角色当前菜单所有权限
		List<Function> functions = curPermissions(wid);
		//初始化 功能列表
		List<Function> editFuns = new ArrayList<Function>();
		//遍历功能
		for(Iterator<Function> f = functions.iterator();f.hasNext();){
			//实体化对象
			Function func = f.next();
			//如果FunCode 等于 edit
			if(func.getCode().equalsIgnoreCase("edit")){
				logger.info("curAutEdit: " + func.getDes());
				//增加到编辑功能中
				editFuns.add(func);
			}
		}
		return editFuns;
	}
	
	public void loadDictData(){
		List<DictionaryVo> dictVos = new ArrayList<DictionaryVo>();
		ServletContext context = ServletActionContext.getServletContext();  
	    HashMap dictMap = (HashMap)context.getAttribute("dictMap");
	    logger.info("dictCode: " + dictCode);
	    HashMap dMap = (HashMap) dictMap.get(dictCode);
	    logger.info("dMap: " + dMap.size());
	    logger.info("dictKey: " + dictKey);
	    
	    String key;
	    String word;
	    
	    if(dictKey.equalsIgnoreCase("")){
	    	for(int i = 0; i < dMap.size(); i++){
	    		DictionaryVo dv = new DictionaryVo();
		    	logger.info("dMap: " + (String)dMap.get("" + (i+1) + ""));
		    	
		    	key = String.valueOf(i+1);
		    	word = (String)dMap.get("" + (i+1) + "");
		    	dv.setKey(key);
		    	dv.setWord(word);
		    	dictVos.add(dv);
		    }
	    }else{
	    	
	    	for(int i = 0; i < dMap.size(); i++){
	    		DictionaryVo dv = new DictionaryVo();
		    	logger.info("dMap: " + (String)dMap.get("" + dictKey + (i+1) + ""));
		    	key = String.valueOf(i+1);
		    	word = (String)dMap.get("" + dictKey + (i+1) + "");
		    	if(EntityUtils.isNotNull(word)){
		    		dv.setKey(key);
			    	dv.setWord(word);
			    	dictVos.add(dv);
		    	}
		    	
		    }
	    	
	    }
	    
	    toWriteArray(dictVos);
	    
	}

	
	public static void main(String[] args) throws SQLException, IOException{

	}
	
	
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 重写ServletResponseAware接口方法
	 */
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;		
	}

	/**
	 * 重写SessionAware接口方法
	 */
	@Override
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}

	/**
	 * Gets And Sets
	 */	
	public int getWid() {
		return wid;
	}


	public void setWid(int wid) {
		this.wid = wid;
	}

	public String getAutCode() {
		return autCode;
	}

	public void setAutCode(String autCode) {
		this.autCode = autCode;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public List<FunctionVo> getFunctions() {
		return functions;
	}

	public void setFunctions(List<FunctionVo> functions) {
		this.functions = functions;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getModelName() {
		return modelName;
	}

	public void setModelName(String modelName) {
		this.modelName = modelName;
	}

	public String getModelIdName() {
		return modelIdName;
	}

	public void setModelIdName(String modelIdName) {
		this.modelIdName = modelIdName;
	}

	public String getAssigneType() {
		return assigneType;
	}

	public void setAssigneType(String assigneType) {
		this.assigneType = assigneType;
	}

	public String getAssigneRoles() {
		return assigneRoles;
	}

	public void setAssigneRoles(String assigneRoles) {
		this.assigneRoles = assigneRoles;
	}

	public String getAssignees() {
		return assignees;
	}

	public void setAssignees(String assignees) {
		this.assignees = assignees;
	}

	public String getDictCode() {
		return dictCode;
	}

	public void setDictCode(String dictCode) {
		this.dictCode = dictCode;
	}

	public String getDictKey() {
		return dictKey;
	}

	public void setDictKey(String dictKey) {
		this.dictKey = dictKey;
	}




}
